package com.panopset;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.xpath.XPathFactory;

import org.xml.sax.InputSource;

/**
 * Maven pom.xml file parser. Trick is to get around the name spaces.
 *
 * @author Karl Dinwiddie
 *
 */
public final class PomParser {

    /**
     * pom file.
     */
    private final File pf;

    /**
     * &quot;pom.xml&quot;.
     */
    public static final String POM_FILE = "pom.xml";

    /**
     * @param file
     *            Maven pom.xml file.
     */
    public PomParser(final File file) {
        pf = file;
    }

    /**
     * @param xpath
     *            XPath to get results from.
     * @return results of parsing pom with the xpath.
     * @throws Exception Exception.
     */
    public String getXPath(final String xpath) throws Exception {
        // XML name spaces are a good idea for some things, but get rid of
        // them if you want to use XPaths.
        String inp = UtilIO.getFileText(pf);
        StringWriter sw = new StringWriter();
        sw.append("<project>");
        String zonk = inp.substring(inp.indexOf("<project"));
        int i = zonk.indexOf(">");
        zonk = zonk.substring(i + 1);
        sw.append(zonk);
        return XPathFactory
                .newInstance()
                .newXPath()
                .evaluate(xpath,
                        new InputSource(new StringReader(sw.toString())));
    }
}
